package com.github.shiqiyue.app.config.security.gapi;

import com.github.shiqiyue.app.common.filter.PathConfigurableFilter;
import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.result.ResultCode;
import com.github.shiqiyue.app.common.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 *
 * @author wenyao.wu
 * @since 2020/9/10
 */
@Slf4j
public class GapiAuthFilter extends PathConfigurableFilter {


    @Override
    protected void doFiltering(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            GapiLoginUser gapiLoginUser = GapiSecurityContext.getLoginInfo(request.getSession());
            if (gapiLoginUser == null) {
                ResponseUtils.populateResponse(ResponseEntity.ok(Result.newInstance("please login", ResultCode.NOT_LOGIN)), response);
                return;
            }

            GapiSecurityContext.set(gapiLoginUser);

            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error("gapi auth filter error", e);
        } finally {
            GapiSecurityContext.clear();
        }
    }

}
